<template>
  <div class="useMapbox">
    <div ref="basicMapbox" :style="mapSize"></div>
    <pre id="info"></pre>
    
    <div class="modal_pic" v-if="openToi">
      <div class="modal_all">
        <div class="modal_title">
          <p>二郎分厕实时数据监测</p>
          <p @click="handleCancel">×</p>
        </div>
        <div class="modal_content">
          <markerInfo></markerInfo>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import mapboxgl from "mapbox-gl";
import MapboxLanguage from "@mapbox/mapbox-gl-language";
import markerInfo from './markerInfo'
import {getToiInfoData} from '../../api'
export default {
  props: {
    mapWidth: {
      type: String,
    },
    mapHeight: {
      type: String,
    },
  },
  components:{
    markerInfo
  },
  data() {
    return {
      iconTest:require('../../assets/img/icon-test.png'),
      openToi:false,
      markersInfo:[]
    };
  },
  mounted() {
    setTimeout(() => {
      this.getMarkersData()
    }, 100);
  },
  methods: {
    async getMarkersData(){
      let res = await getToiInfoData()
      this.markersInfo = res
      this.init();
    },
    handleCancel() {
      this.$store.commit('closePic')
      this.openToi = false;
    },
    // 初始化
    init() {
      mapboxgl.accessToken =
        "pk.eyJ1IjoiZ2FvamllbWFwYm94IiwiYSI6ImNrZ2FtM295cjAzemkyeXFveGdkbzViNjUifQ._nJ2ukz1Ys2oPb_-5u-tng";
      // 英文标注转换为中文
      // mapboxgl.setRTLTextPlugin(
      //   "https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.1.0/mapbox-gl-rtl-text.js"
      // );
      const map = new mapboxgl.Map({
        container: this.$refs.basicMapbox,
        style: "mapbox://styles/mapbox/streets-v9",
        center: [106.46252977659412, 29.507215380953383],
        pitch: 0, //地图的角度，不写默认是0，取值是0-60度，一般在3D中使用
        zoom: 14,
      });
      // 设置语言
      var language = new MapboxLanguage({ defaultLanguage: "zh" });
      map.addControl(language);

      // 地图导航
      var nav = new mapboxgl.NavigationControl();
      map.addControl(nav, "top-left");
      // 比例尺
      var scale = new mapboxgl.ScaleControl({
        maxWidth: 80,
        unit: "imperial",
      });
      map.addControl(scale);
      scale.setUnit("metric");
      // 全图
      map.addControl(new mapboxgl.FullscreenControl());
      // 使用定位模块
      map.addControl(
        new mapboxgl.GeolocateControl({
          positionOptions: {
            enableHighAccuracy: true,
          },
          trackUserLocation: true,
          showUserLocation: true,
          zoom: 14,
        })
      );
      // 建立一个标记点
      var marker = new mapboxgl.Marker({
        draggable: true,
      });
      //   .setLngLat([0, 0]);//添加marker的初始化点
      //   .addTo(map);//在哪个地图中添加
      function onDragEnd() {
        var lngLat = marker.getLngLat();
        coordinates.style.display = "block";
        coordinates.innerHTML =
          "Longitude: " + lngLat.lng + "<br />Latitude: " + lngLat.lat;
      }
      var el = document.createElement('div');
      el.style.backgroundImage = `url(${this.iconTest})`;
      el.style.backgroundSize = '100% 100%';
      el.style.width = 40 + 'px';
      el.style.height = 40 + 'px';

      new mapboxgl.Marker(el)
        .setLngLat([this.markersInfo[2].longitude, this.markersInfo[2].latitude])
        .addTo(map);

      el.addEventListener('click', this.handleKitten, false);
      map.on('click', this.handleMapClick);
      marker.on("dragend", onDragEnd);
      // 点击获取经纬度模块&点击标记点
    //   map.on("click", function (e) {
    //     document.getElementById("info").innerHTML =
    //       JSON.stringify(e.point) + "<br />" + JSON.stringify(e.lngLat);
    //     marker.setLngLat([e.lngLat.lng, e.lngLat.lat]).addTo(map);
    //   });
      //   map.addControl(
      //     new mapboxgl.MapboxGeocoder({
      //       accessToken: mapboxgl.accessToken,
      //     })
      //   );
      map.on("load", function () {
        //on设置监听，以及触发时的回调，这是加载时的触发的生成3d地图的例子
        // Insert the layer beneath any symbol layer.
        var layers = map.getStyle().layers;

        var labelLayerId;
        for (var i = 0; i < layers.length; i++) {
          if (layers[i].type === "symbol" && layers[i].layout["text-field"]) {
            labelLayerId = layers[i].id;
            break;
          }
        }

        map.addLayer(
          //在地图样式中添加一个Mapbox样式图层。(图层，layerid)
          {
            id: "3d-buildings",
            source: "composite",
            "source-layer": "building",
            filter: ["==", "extrude", "true"],
            type: "fill-extrusion",
            minzoom: 15,
            paint: {
              "fill-extrusion-color": "#aaa",

              // use an 'interpolate' expression to add a smooth transition effect to the
              // buildings as the user zooms in
              "fill-extrusion-height": [
                "interpolate",
                ["linear"],
                ["zoom"],
                15,
                0,
                15.05,
                ["get", "height"],
              ],
              "fill-extrusion-base": [
                "interpolate",
                ["linear"],
                ["zoom"],
                15,
                0,
                15.05,
                ["get", "min_height"],
              ],
              "fill-extrusion-opacity": 0.6,
            },
          },
          labelLayerId
        );
      });
    },
    handleKitten(e) {
      e.target.style.backgroundImage = `url(${this.iconTest})`;
      e.target.style.backgroundSize = '100% 100%';
      e.stopPropagation();
      this.openToi = true;
      this.$store.commit('openPic')
    },
    handleMapClick(e) {
      console.log('handleMapClick', e);
    }
  },
  computed: {
    mapSize() {
      let styleObj = {
        width: this.mapWidth,
        height: this.mapHeight,
      };
      return styleObj;
    },
  },
};
</script>
<style lang="less">
.useMapbox {
  @keyframes myfirst
    {
        0%   {transform: scale(.2);}
        100%   {transform: scale(1);}
    }
  width: 100%;
  height: 80vh;
  position: relative;
  .modal_pic{
    width: 100%;
    height: 80vh;
    position: absolute;
    left: 0;
    top: 0;
    z-index: 99;
    background-color: rgba(0,0,0,.45);
    position: absolute;
    top: 0;
    .modal_all{
      animation: myfirst .5s;
      width: 30%;
      height: 30%;
      position: absolute;
      margin: auto;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      background: white;
    }
    .modal_title{
      width: 100%;
      height: 10%;
      text-align: center;
      p{
        display: inline-block;
        line-height: 5vh;
        margin: 0;
      }
      p:nth-of-type(1){
        font-family: cursive;
        font-weight: bolder;
        font-size: 22px;
      }
      p:nth-of-type(2){
        float: right;
        cursor: pointer;
        margin-right: 22px;
        font-size: 30px;
      }
    }
    .modal_content{
      width: 100%;
      height: 90%;
    }
  }
}
.mapboxgl-map {
  height: 100%;
  width: 100%;
}
</style>
